package 出现次数最多的子树元素和508;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 谢阳
 * @version 1.8.0_131
 */
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    private int max = 1;
    private HashMap<Integer, Integer> map = new HashMap<>();

    public int[] findFrequentTreeSum(TreeNode root) {
        dfs(root);
        Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
        int count = 0;
        for (Map.Entry<Integer, Integer> entry : entries) {
            if (entry.getValue() == max) {
                count++;
            }
        }

        int[] res = new int[count];
        count = 0;
        for (Map.Entry<Integer, Integer> entry : entries) {
            if (entry.getValue() == max) {
                res[count++] = entry.getKey();
            }
        }

        return res;

    }

    private int dfs(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int left = dfs(node.left);
        int right = dfs(node.right);
        int sum =node.val + right + left;
        map.put(sum, map.getOrDefault(sum, 0) + 1);
        max = Math.max(max, map.get(sum));
        return sum;
    }
}